<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use apiend\models\User;
use common\logics\SmsCaptchaForm;

/**
 * Password reset request form
 */
class PasswordForgetRequestForm extends Model {

    public $mobile;
    public $captcha;
    public $password;
    //
    private $_user = null;

    const PASSWORD_PATTERN = '/((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{8,16}/i';

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['mobile', 'trim'],
            [['mobile', 'captcha', 'password'], 'required'],
//            [['password'], 'match', 'pattern' => self::PASSWORD_PATTERN, 'message' => '密码过于简单'],
            ['password', 'string', 'min' => 6, 'max' => 16],
            ['mobile', '\common\validators\MobileValidator'],
            ['mobile', 'validateUser'],
            ['captcha', 'validateCaptcha'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateUser($attribute) {
        if (!$this->hasErrors()) {
            if (!$this->getUser()) {
                $this->addError($attribute, '手机号未注册，对应的帐号不存在');
            }
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptcha($attribute) {
        if (!$this->hasErrors()) {
            $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_FORGET . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '已过期');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByMobile($this->mobile);
        }
        return $this->_user;
    }

    /**
     * Sends an email with a link, for resetting the password.
     *
     * @return bool whether the email was send
     */
    public function send() {
        if (!$this->validate()) {
            $this->dumpError('参数校验失败');
        }
        $user = $this->getUser();
        if (!$user) {
            return false;
        }
        $user->setPassword($this->password);
        $user->removePasswordResetToken();
        return $user->save();
    }

}
